import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition 测试类
 * 用法等同于 传统线程的 wait()--现在的-->await();
 *                    notify/All()--现在的-->signal();
 * 优势是方便做多线程多个condition 控制三个以上线程执行
 */
public class ConditonCommunication {

	public static void main(String[] args) {
		
		final Businiss businiss = new Businiss();
		
		new Thread(new Runnable(){
			public void run() {
				for(int i=0;i<10;i++){
					businiss.sub(i);
				}
			}
		}).start();
		
		for(int i=0;i<10;i++){
			businiss.main(i);
		}
		
	}
	
	static class Businiss {
		boolean bShouldSub = false;
		Lock lock = new ReentrantLock(); 
		Condition condition = lock.newCondition(); 
		public /*synchronized*/ void main(int loop) {
			lock.lock();
			try{
				while(bShouldSub){
					try {
//						this.wait();
						condition.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for(int i=0;i<10;i++){
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("main " + i +" of loop: " + loop);
				}
				bShouldSub = true;
//				this.notify();
				condition.signal();
			}finally{
				lock.unlock();
			}
			
		}
		
		public /*synchronized*/ void sub(int loop) {
			lock.lock();
			try{
				while(!bShouldSub){
					try {
//						this.wait();
						condition.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for(int i=0;i<10;i++){
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("sub " + i +" of loop: " + loop);
				}
				bShouldSub = false;
//				this.notify();
				condition.signal();
			}finally{
				lock.unlock();
			}
			
		}
		
	}

}
